import React, { useEffect, useRef, useState } from "react";
import * as echarts from "echarts";

interface LineContentProps {
  record: any;
  showTarget: boolean;
}

const baseOptions = {
  itemStyle: {
    borderRadius: 10,
  },
  grid: {
    left: "40",
    right: "30",
    bottom: "30",
    top: "30",
  },
};
const TestChart: React.FC<LineContentProps> = ({ record, showTarget }) => {
  const echartsRef = useRef<HTMLDivElement | null>(null);
  const myChartRef = useRef<echarts.EChartsType | null>(null);
  const referenceDivRef = useRef<HTMLDivElement>(null);

  const setCharts = (record: any) => {
    if (myChartRef.current) {
      myChartRef.current.clear();
      myChartRef.current.resize();
    } else {
      myChartRef.current = echarts.init(echartsRef.current);
    }
    var data = [
      {
        normalTime: [
          [
            "2025-03-14 11:46:40",
            "2025-03-14 11:51:40",
            "2025-03-14 11:56:40",
            "2025-03-14 12:01:40",
            "2025-03-14 12:06:40",
          ],
          [
            "2025-03-15 00:46:40",
            "2025-03-15 00:51:40",
            "2025-03-15 00:56:40",
            "2025-03-15 01:01:40",
            "2025-03-15 01:06:40",
          ],
        ],
        name: "BHDR.CDY6.RCY1",
        normalValue: [
          ["42.21", "42.29", "42.23", "42.26", "42.34"],
          ["28.88", "32.71", "36.35", "42.21", "42.36"],
        ],
        anomalyTime: [
          "2025-03-14 20:26:40",
          "2025-03-14 20:31:40",
          "2025-03-14 20:36:40",
          "2025-03-14 20:41:40",
          "2025-03-14 20:46:40",
        ],
        anomalyValue: ["42.22", "42.31", "42.26", "42.34", "42.23"],
      },
      {
        normalTime: [
          [
            "2025-03-14 11:46:40",
            "2025-03-14 11:51:40",
            "2025-03-14 11:56:40",
            "2025-03-14 12:01:40",
            "2025-03-14 12:06:40",
          ],
          [
            "2025-03-15 00:46:40",
            "2025-03-15 00:51:40",
            "2025-03-15 00:56:40",
            "2025-03-15 01:01:40",
            "2025-03-15 01:06:40",
          ],
        ],
        name: "BHDR.CDY6.RCY2",
        anomalyValue: ["60.35", "60.31", "60.26", "60.34", "60.23"],
      },
      {
        normalTime: [
          [
            "2025-03-16 11:46:40",
            "2025-03-16 11:51:40",
            "2025-03-16 11:56:40",
            "2025-03-16 12:01:40",
            "2025-03-16 12:06:40",
          ],
          [
            "2025-03-17 00:46:40",
            "2025-03-17 00:51:40",
            "2025-03-17 00:56:40",
            "2025-03-17 01:01:40",
            "2025-03-17 01:06:40",
          ],
        ],
        name: "BHDR.CDY6.RCY3",
        normalValue: [
          ["56.21", "56.29", "56.23", "56.26", "56.34"],
          ["28.88", "28.71", "28.35", "28.19", "28.27"],
        ],
        anomalyTime: [
          "2025-03-22 20:26:40",
          "2025-03-22 20:31:40",
          "2025-03-22 20:36:40",
          "2025-03-22 20:41:40",
          "2025-03-22 20:46:40",
        ],
        anomalyValue: ["50.22", "50.31", "50.26", "50.34", "50.23"],
      },
    ];
    // 准备所有系列数据
    const series: any[] = [];
    const legendData: any[] = [];

    // 获取所有时间点用于确定x轴范围
    let allTimes: any[] = [];

    // 为每个参数创建系列
    data.forEach((item, index) => {
      // 合并所有数据点为一个连续的序列
      const combinedData: any[] = [];

      // 处理第一组正常数据
      item.normalTime.forEach((array, index) => {
        array.forEach((time, i) => {
          const dateTime = new Date(time);
          allTimes.push(dateTime);
          combinedData.push({
            time: dateTime,
            value:
              item.normalValue && item.normalValue[index]
                ? item.normalValue[index][i]
                : null,
            isAnomaly: false,
          });
        });
      });

      if (item.anomalyTime) {
        // 处理异常数据
        item.anomalyTime.forEach((time, i) => {
          const dateTime = new Date(time);
          allTimes.push(dateTime);
          combinedData.push({
            time: dateTime,
            value: item.anomalyValue[i],
            isAnomaly: true,
          });
        });
      }

      // 按时间排序
      combinedData.sort((a, b) => a.time - b.time);

      // 提取排序后的数据
      const sortedData = combinedData.map((d) => [d.time, d.value]);

      // 创建标记点数组，用于在图表上标记异常区域的开始和结束
      const markAreaData: any[] = [];
      let anomalyStart = null;

      for (let i = 0; i < combinedData.length; i++) {
        // 找到异常区域的开始
        if (
          combinedData[i].isAnomaly &&
          (i === 0 || !combinedData[i - 1].isAnomaly)
        ) {
          anomalyStart = combinedData[i].time;
        }
        // 找到异常区域的结束
        else if (
          !combinedData[i].isAnomaly &&
          i > 0 &&
          combinedData[i - 1].isAnomaly
        ) {
          if (anomalyStart) {
            markAreaData.push([
              { xAxis: anomalyStart },
              { xAxis: combinedData[i].time },
            ]);
            anomalyStart = null;
          }
        }
      }

      // 如果异常区域一直到数据结束
      if (anomalyStart) {
        markAreaData.push([
          { xAxis: anomalyStart },
          { xAxis: combinedData[combinedData.length - 1].time },
        ]);
      }

      // 添加合并后的数据系列
      series.push({
        name: item.name,
        type: "line",
        showSymbol: false,
        lineStyle: {
          width: 2,
          type: "solid",
        },
        data: sortedData,
        connectNulls: true,
        markArea: {
          itemStyle: {
            // 使用偏红色阴影标记异常区域
            color: "rgba(255, 50, 50, 0.15)",
            borderWidth: 1,
            borderType: "dashed",
          },
          data: markAreaData,
        },
      });

      // 添加到图例
      if (!legendData.includes(item.name)) {
        legendData.push(item.name);
      }
    });

    // 确定x轴的最小值和最大值
    const sortedTimes = allTimes.sort((a, b) => a - b);
    const minTime = sortedTimes[0];
    const maxTime = sortedTimes[sortedTimes.length - 1];

    const option = {
      title: {
        text: "设备异常检测",
        left: "center",
      },
      tooltip: {
        trigger: "axis",
        formatter: function (params: any) {
          let result = "";
          if (params[0] && params[0].axisValue) {
            const date = new Date(params[0].axisValue);
            result = `${date.toLocaleString()}<br/>`;
          }

          // 对参数进行分组，确保相同名称的系列只显示一次
          const groupedParams = {};
          params.forEach((param: any) => {
            if (param.seriesName && param.value) {
              // 判断是正常还是异常数据（根据线型）
              const isAnomaly = param.seriesIndex % 3 === 1; // 异常数据的索引余3为1
              const key =
                param.seriesName + "-" + (isAnomaly ? "anomaly" : "normal");

              if (
                !groupedParams[key] ||
                Math.abs(param.value[1]) > Math.abs(groupedParams[key].value[1])
              ) {
                groupedParams[key] = param;
                // 添加标记是否为异常数据
                groupedParams[key].isAnomaly = isAnomaly;
              }
            }
          });
          // 显示分组后的参数
          Object.values(groupedParams).forEach((param: any) => {
            if (param.value[1]) {
              result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>`;
              result += `${param.seriesName}: ${parseFloat(
                param.value[1]
              ).toFixed(2)}<br/>`;
            }
          });

          return result;
        },
      },
      legend: {
        data: legendData,
        top: 30,
        type: "scroll",
        selector: false,
        formatter: function (name) {
          return name;
        },
      },
      grid: {
        left: "5%",
        right: "5%",
        bottom: "15%",
        containLabel: true,
      },
      xAxis: {
        type: "time",
        boundaryGap: false,
        min: minTime,
        max: maxTime,
        axisLabel: {
          formatter: function (value) {
            const date = new Date(value);
            return `${
              date.getMonth() + 1
            }-${date.getDate()} ${date.getHours()}:${date
              .getMinutes()
              .toString()
              .padStart(2, "0")}`;
          },
          rotate: 60,
          margin: 15,
        },
      },
      yAxis: [
        {
          type: "value",
          min: "dataMin",
          max: "dataMax",
          axisLabel: {
            formatter: function (value) {
              return value !== undefined
                ? parseFloat(`${value}`).toFixed(2)
                : "";
            },
          },
        },
      ],
      series: series,
      dataZoom: [
        {
          type: "inside",
          start: 0,
          end: 100,
          zoomOnMouseWheel: true,
          moveOnMouseMove: true,
        },
      ],
    };
    myChartRef.current.setOption(option);
  };

  useEffect(() => {
    if (!referenceDivRef.current) return;
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width, height } = entry.contentRect;
        setDimensions({
          refHeight: height,
          refWidth: width,
        });
      }
    });
    resizeObserver.observe(referenceDivRef.current);
    return () => {
      resizeObserver.disconnect();
    };
  }, []);

  const [dimensions, setDimensions] = useState({
    refHeight: 0,
    refWidth: 0,
  });

  useEffect(() => {
    if (record) {
      setCharts(record);
    }
  }, [record, dimensions]);

  return (
    <div ref={referenceDivRef}>
      <div
        style={{
          margin: "auto",
          height: "20rem",
          marginBottom: "0.8rem",
        }}
        ref={echartsRef}
      ></div>
    </div>
  );
};

export default TestChart;
